var gridForm = {
		  events :{ 
			 dataSourceCode	: //数据源事件
				 [{event:"change",method:function(event)
					 {  
						 var newVal = $(event.target).val();
						 if(!newVal && newVal !== 0) return ;
						 $.ajax({
							 url:"/grid/queryFormTable",
							 data:{dataSourceCode:newVal},
							 success:function(response){
								 var data = [];
								 $.each(response.data,function(index,obj){
									 data.push({key:obj,value:obj});
								 })
								 $("#autoGridForm").selfform("setData","tableName",data);
							 }
						 }) 
				     }
				 }],
			 queryType	: // 查询类型 
				 [{event:"change",method:function(event)
					 {  
						 var newVal = $(event.target).val();
						 var flag = newVal == "1" ? false :true; 
						 $("#autoGridForm").selfform("disable",['customerSql','customerCountSql','customerColumnSql'],flag);  
						 $("#autoGridForm").selfform("disable",["tableName"],(!flag));   
				     }
				 }],
			analysis ://解析sql
				[{event:"click",target:".confirm",method:function(event)
					{ 
					 analysis("sql","customerSql");
				   }
				}]
		  }
}




var formConfig = function (response){  
	 var systems = response.systems;
	 var dataSources = response.dataSources;
	 var dictionarys = $.dictionaryUtil.formatArray(response.dictionarys);  
     return { 
         lableWidth:  150,
		 elementWidth:200,     
		 models : [
			 {field:"systemCode",lable:"所属系统",type:"select",search:true,
			  options:{ validate:{require:true} ,data:systems,key:"code",value:"name"/*,events:gridForm.events.systemCode*/}
			 },
			 {field:"dataSourceCode",lable:"数据源",type:"select",search:true,
			  options:{validate:{require:true},data:dataSources,key:"code",value:"name",events:gridForm.events.dataSourceCode}
			 },
			 {field:"code",lable:"表格编码",type:"text",options:{validate:{require: true}}},
			 
			 {field:"name",lable:"名称",type:"text",options:{validate:{require: true}}}, 
			 {field:"tableName",lable:"表",type:"select",options:{key:"key",value:"value"}},
			 {field:"queryType",lable:"自定义sql",type:"select",
			  options:{validate:{require: true},key:"key",value:"value",data:dictionarys['grid_query_type'],events:gridForm.events.queryType}
			 },
			 {field:"isPaging",lable:"是否分页",type:"radio",value:1,
				 options:{key:"key",value:"value",data:dictionarys['grid_is_paging']}
			 },  
			 {field:"selectType",lable:"选中方式",type:"radio",value:1,
				 options:{key:"key",value:"value",data:dictionarys['grid_select_type']}
			 },
			 {field:"isInitQuery",lable:"是否初始化",type:"radio",value:1,
				 options:{key:"key",value:"value",data:dictionarys['grid_is_init_query']}
			 },
			 {field:"isRowNumber",lable:"是否显示行号",type:"radio",value:1,
				 options:{key:"key",value:"value",data:dictionarys['grid_is_row_number']}
			 },
	 
			 {field:"operation",lable:"操作",type:"checkbox",
				 options:{key:"key",value:"value",data:dictionarys['grid_operation']}
			 },  
			 {field:"单选",lable:"radio测试",type:"radio",value:1,
				 options:{key:"key",value:"value",data:dictionarys['grid_is_row_number']}
			 }, 
			 {field:"myDate",lable:"时间",type:"date",
				   options:{events:[{event:"click",method:WdatePicker,param:{dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true}}]}
			 }, 
			 {field:"myDate2",lable:"时间",type:"date",
				 options:{css:"Wdate",events:[{event:"click",method:WdatePicker,param:{dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true}}]}
			 },   
		 
			 {field:"customerSql",lable:"SQL",type:"textarea",colspan:2,value:"select * from base_user"}, 
			 
	    	 {field:"analysis",lable:"解析",type:"custom",options:{events:gridForm.events.analysis},
				 value:"<input type='button' class='confirm' style='position:absolute;margin-top: -40px;' value='解析'>"
			 } , 
			
/* 			, {field:"customerCountSql",lable:"数量SQL",type:"textarea"},
			 {field:"analysisCountSql",lable:"解析",type:"button",options:{css:"confirm",events:[{click:function(event){
				 analysis("count","customerCountSql");
			 }}]}},  */
		   ],
        }
     }; 

     
 var analysis	= function (type,sqlElement){ 
 
		 var elements = {"systemCode":null,"dataSourceCode":null,'queryType':null},flag = false;
		 for(var e in elements){
			 var val =  $("#autoGridForm").selfform("getData",e);
			 if(!val){
				 var tip =  $("#autoGridForm [name='"+e+"']").easytip();
				 tip.show("不能为空！");
				 flag = true;
			 }
		     elements[e] = val; 
		  }
		 
		 
		 if(flag) return;
		 
		 var sql             =  $("#autoGridForm").selfform("getData",sqlElement);
	         tableName       =  $("#autoGridForm").selfform("getData","tableName");
	         dataSourceCode  =  $("#autoGridForm").selfform("getData","dataSourceCode"); 
	         queryType       =  $("#autoGridForm").selfform("getData","queryType"); 
	         
	     var data =   {dataSourceCode:dataSourceCode,queryType:queryType,tableName:tableName,sql:sql};

		 $.ajax({
			 url : "/grid/queryGridColumn",
			 data:data,
			 success:function(response){
				 
				 response = response.data;
				 
				 if(!response || response.length < 1) return ;
				 
				 var updateRows = [] ,insertRows = [] , result = $("#mytabel").selfgrid("getAllData"); 
 
				 if(result && result.length > 0  ){
					  var insertRows = [];
					 
					  for(var j = 0 , ll = response.length ; j < ll ; j++){
						  
						  var f = true , res = response[j]; 
						  
					      for(var i = 0 , l = result.length ; i < l ; i++){
						 
							   if(res.columnName == result[i].columnName){ 
								   f = false;
								   res =  $.extend({},result[i],res);
							       updateRows.push({rowIndex : i , data : res}); 
								   break;
							    };
						  }
					      
						  if(f) insertRows.push(res); 
					    } 
						  
					  }else{ 
						  insertRows =  response   ;
					  } 
				 
				 if(insertRows.length > 0){
					 $("#mytabel").selfgrid("addRows",insertRows);  
				 }
				 
				 if(updateRows.length > 0 ){
					 $("#mytabel").selfgrid("updateRows",updateRows);  
					 
				 } 
			 }
		 })
	 }
 
var confirm = function(){ 
	var form = $("#autoGridForm");
	var flag = form.selfform("validate");
	if(!flag){
		return flag ;
	}
	var formData = form.selfform("getData");
	var gridData =  $("#mytabel").selfgrid("getAllData");
	$.ajax({
		   url  :"/grid/save",
		   type :"post",
		   contentType:"application/json",
		   data : JSON.stringify({"grid":formData,"details":gridData}),
		   success:function(response)
		   {  
			 alert("success");
		   }
	})   
}

$(function(){
	$.ajax({
		url:"/grid/queryFormUpdate",
		   success:function(response)
		   {  
			 $("#autoGridForm").selfform(formConfig(response.data));
		   }
	})  
	
	$(".autoGridFormConirm").on("click",function(){
		confirm();
	})
});
 